package p.ithorns.sample.minio;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import p.ithorns.framework.minio.model.UploadReq;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * TestController
 * <p>
 * TODO 分片 断点续传
 * 参考：
 * https://gitee.com/ninesuntec/large-file-upload
 * https://github.com/sky-boom/minio-spring-boot-starter
 * <p>
 * 前端使用blake3库：https://www.npmjs.com/package/blake3
 * npm install blake3-wasm
 *
 * @author liuhaitao
 * @date 2024/4/7 10:48
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class TestController {

    private final MinioService service;

    @PostMapping("/upload2")
    public String upload(UploadReq req) {
        MultipartFile file = req.getFile();
        log.info(req.toString());
        return "ok";
    }

    /**
     * 文件上传
     *
     * @param file
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file,
                         @RequestPart(value = "meta", required = false) Object meta) {
        return service.upload(file, meta);
    }

    /**
     * 删除
     *
     * @param fileName -
     */
    @DeleteMapping("/")
    public void delete(@RequestParam("fileName") String fileName) throws Exception {
        service.remove(fileName);
    }

    /**
     * 获取文件信息
     *
     * @param fileName -
     * @return String
     */
    @GetMapping("/info")
    public String getFileStatusInfo(@RequestParam("fileName") String fileName) throws Exception {
        return service.getStatus(fileName);
    }

    /**
     * 获取文件外链
     *
     * @param fileName -
     * @return String
     */
    @GetMapping("/url")
    public String getPresignedObjectUrl(@RequestParam("fileName") String fileName) throws Exception {
        return service.getUrl(fileName);
    }

    /**
     * 文件下载
     *
     * @param fileName -
     * @param response -
     */
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            InputStream fileInputStream = service.download(fileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(fileInputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载失败");
        }
    }

}